﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NETMovie.Entities;
using System.Collections;

namespace NETMovie.Repositories.EF
{
    public class UserRepository : AbstractRepository, IUserRepository
    {
        public UserRepository()
        {
            base.Initialize();
        }

        public User GetUser(string username)
        {
            var user = cntx.Users.FirstOrDefault(m => m.UserName == username);
            if (user != null)
            {
                // Explicitly load the country
                Country country = user.Country;
            }

            return user;
        }

        public bool CreateUser(User user)
        {
            // Need to refresh the Country in the same context
            Country dbCountry = GetCountry(user.Country.CountryCode);
            user.Country = dbCountry;

            cntx.AddToUsers(user);
            cntx.SaveChanges();
            
            return true;
        }

        public bool UpdateUser(User user)
        {
            // Need to refresh the User in the same context
            User dbUser = GetUser(user.UserName);
            dbUser.Update(user);

            // Need to refresh the Country in the same context
            Country dbCountry = GetCountry(user.Country.CountryCode);
            dbUser.Country = dbCountry;

            cntx.SaveChanges();

            return true;
        }

        public Country[] GetCountries()
        {
            List<Country> dbCountries = cntx.Countries.ToList<Country>();
            if (dbCountries == null || dbCountries.Count == 0)
                return null;

            return dbCountries.ToArray();
        }

        public Country GetCountry(string countryCode)
        {
            Country country = cntx.Countries.FirstOrDefault(m => m.CountryCode == countryCode);
            return country;
        }
    }
}
